package com.dingmouren.example.layoutmanagergroup.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.dingmouren.example.layoutmanagergroup.R;
import com.dingmouren.example.layoutmanagergroup.widget.DraaggableView;
import com.dingmouren.example.layoutmanagergroup.widget.FlipCardAnimation;
import com.dingmouren.layoutmanagergroup.echelon.EchelonLayoutManager;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 钉某人
 * github: https://github.com/DingMouRen
 * email: naildingmouren@gmail.com
 * 梯形布局
 */
public class EchelonFragment extends Fragment {
    private boolean showLog = false;
    public static RecyclerView mRecyclerView;
    private EchelonLayoutManager mLayoutManager;
    private CircleImageView tv_nickname;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_echelon,container,false);
        mRecyclerView = rootView.findViewById(R.id.recycler_view);
        tv_nickname = rootView.findViewById(R.id.img_user);
        tv_nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e("####", "============================ 1111111111");
//                    mRecyclerView.smoothScrollToPosition(1);
//                mLayoutManager.smoothScrollToPosition(mRecyclerView, new RecyclerView.State(), -30);
                mRecyclerView.smoothScrollBy(0, -1370);
//                mRecyclerView.smoothScrollToPosition(0);
//                startCountDownTimer();
            }
        });
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (showLog) {
                    Log.e("========", "=====================ontouch");
                }

                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_UP:
//                        startDelay();
                        break;
                    case MotionEvent.ACTION_MOVE:
//                        if (showLog) {
                            Log.e("========", "=====================ontouch ACTION_MOVE");
//                        }
                        EchelonLayoutManager.isSlide = true;
                        break;
                }

                return false;
            }
        });

//        mRecyclerView.setOnFlingListener(new RecyclerView.OnFlingListener() {
//            @Override
//            public boolean onFling(int velocityX, int velocityY) {
//                if (showLog) {
//                    Log.e("========","======== setOnFlingListener onFling");
//                }
//                return true;
//            }
//        });
    }

    private void initData() {
//        mLayoutManager = new EchelonLayoutManager(getContext());
        mLayoutManager = new EchelonLayoutManager(getContext()){
            @Override
            public boolean canScrollVertically() {
                return true;
            }

        };
        mLayoutManager.setStackFromEnd(true);
        mRecyclerView.setLayoutManager(mLayoutManager);


        mRecyclerView.setAdapter(new MyAdapter());
        DraaggableView.curItemCount = mRecyclerView.getAdapter().getItemCount();
//        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                //停止滚动
////                public static final int SCROLL_STATE_IDLE = 0;
////
////                //正在被外部拖拽,一般为用户正在用手指滚动
////                public static final int SCROLL_STATE_DRAGGING = 1;
////
////                //自动滚动开始
////                public static final int SCROLL_STATE_SETTLING = 2;
//
//
//
////                Log.i(this.getClass().getName(),"111111111111111111111111111111111111newState==="+newState);
//            }
//
//            @Override
//            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {  //dx : 水平滚动距离 dy : 垂直滚动距离
//                super.onScrolled(recyclerView, dx, dy);
//
////                Log.i(this.getClass().getName(),"111111111111111111111111111111111111dy==="+dy);
//            }
//        });

    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
        private int[] icons = {R.mipmap.header_icon_1,R.mipmap.header_icon_2,R.mipmap.header_icon_3,R.mipmap.header_icon_4};
        private int[] bgs = {R.mipmap.bg_1,R.mipmap.bg_2,R.mipmap.bg_3,R.mipmap.bg_4};
        private String[] nickNames = {"左耳近心","凉雨初夏","稚久九栀","半窗疏影"};
        private String[] descs = {
                "回不去的地方叫故乡 没有根的迁徙叫流浪...",
                "人生就像迷宫，我们用上半生找寻入口，用下半生找寻出口",
                "原来地久天长，只是误会一场",
                "不是故事的结局不够好，而是我们对故事的要求过多",
                "只想优雅转身，不料华丽撞墙"
        };
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_echelon,parent,false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            holder.icon.setImageResource(icons[position%4]);
            holder.nickName.setText(nickNames[position%4]);
            holder.desc.setText(descs[position%5]);
            holder.bg.setImageResource(bgs[position%4]);

//            holder.view.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    startAnimation(null,view,position);
//                }
//            });

//            ((DraggableFlipView)holder.view).setOnAnimationEndListener(new DraggableFlipView.AnimationEndListener(){
//
//                @Override
//                public void onAnimationEnd() {
//                    Log.i(this.getClass().getName(),"2222222222222222222222222222222222");
////                    mLayoutManager.scrollToPositionWithOffset(6, 0);
////                    mRecyclerView.scrollToPosition(6);
//                    mRecyclerView.smoothScrollToPosition(1);
//                }
//            });


            ((DraaggableView)holder.view).setOnAnimationEndListener(new DraaggableView.AnimationEndListener(){

                @Override
                public void onAnimationEnd() {
                    Log.e("####", "============================ onAnimationEnd");
//                    mRecyclerView.smoothScrollToPosition(1);
//                    mLayoutManager.smoothScrollToPosition(mRecyclerView, new RecyclerView.State(), 0);
//                    mLayoutManager.scrollVerticallyBy(10,mRecyclerView.Recycler, new RecyclerView.State())；
//                    mRecyclerView.scrollBy(0, -50);
                    mRecyclerView.smoothScrollBy(0, -EchelonLayoutManager.mItemViewHeight);// 1370
//                    mRecyclerView.smoothScrollToPosition(-2);
//                    startCountDownTimer();
                }
            });

        }

        @Override
        public int getItemCount() {
            return 10;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            View view;
            ImageView icon;
            ImageView bg;
            TextView  nickName;
            TextView desc;
            public ViewHolder(View itemView) {
                super(itemView);
                view = itemView;
                icon = itemView.findViewById(R.id.img_icon);
                bg = itemView.findViewById(R.id.img_bg);
                nickName = itemView.findViewById(R.id.tv_nickname);
                desc = itemView.findViewById(R.id.tv_desc);

            }
        }
    }


    CountDownTimer countDownTimer;
    private void startCountDownTimer(){

        countDownTimer =  new CountDownTimer(10000,10){

            @Override
            public void onTick(long l) {
               Log.e("==========", "=============== l: "+l+" EchelonLayoutManager.bottomItemVisibleHeight: "+EchelonLayoutManager.bottomItemVisibleHeight);
               if (EchelonLayoutManager.bottomItemVisibleHeight!=0 && EchelonLayoutManager.bottomItemVisibleHeight<5) {
                   countDownTimer.cancel();
               } else {
                   mRecyclerView.smoothScrollToPosition(0);
               }
            }

            @Override
            public void onFinish() {

            }
        }.start();
    }

//    CountDownTimer delay;
//    private void startDelay(){
//
//        delay =  new CountDownTimer(1000,500){
//
//            @Override
//            public void onTick(long l) {
//                if (showLog) {
//                    EchelonLayoutManager.isSlide = false;
//                    Log.e("====","================ startDelay onTick");
//                }
//
//            }
//
//            @Override
//            public void onFinish() {
//                EchelonLayoutManager.isSlide = false;
//                if (showLog) {
//                    EchelonLayoutManager.isSlide = false;
//                    Log.e("","================ startDelay onFinish");
//                }
//                delay = null;
//            }
//        }.start();
//    }

    private void startAnimation(FlipCardAnimation animation, View view,final int position) {
        if (animation != null) {
            animation.setCanContentChange();
            view.startAnimation(animation);
        } else {
            int width = view.getWidth() / 2;
            int height = view.getHeight() / 2;
            animation = new FlipCardAnimation(0, -90, width, height);
            animation.setInterpolator(new AnticipateOvershootInterpolator());
            animation.setDuration(2000);
            animation.setFillAfter(true);
//            animation.setRepeatCount(-1);       //循环翻转
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
//                    mRecyclerView.scrollToPosition(60-position);
//                    mRecyclerView.smoothScrollToPosition(60-position);
                    Log.i(this.getClass().getName(),"111111111111111111111position======"+position);

                    MoveToPosition(60-position);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
//                    ((FlipCardAnimation)animation).setCanContentChange();   //循环翻转

                }

            });
            view.startAnimation(animation);
        }
    }

    public void MoveToPosition(int n) {

//        mLayoutManager.scrollToPositionWithOffset(n, 0);
//
//        mLayoutManager.setStackFromEnd(true);

        mLayoutManager.scrollToPositionWithOffset(3, 0);


    }

}
